#!/usr/bin/python

import platform.plurklib
import urllib
import json

def fix_fucking_json(content):
        content = content.lstrip('CometChannel.scriptCallback(')
        content = content.rstrip(');')
        return content;

class PlurkPlatform(platform.plurklib.PlurkAPI):

    def __init__(self,key):
        super().__init__(key)
        self.__offset = 0
        self.__user_channel = None

    def listen_new_post(self):

        request = urllib.request.Request(url = self.__make_new_listen_url())
        result = urllib.request.urlopen(request)

        result = result.read().decode("utf-8")
        result = json.loads( fix_fucking_json(result) )
        self.__offset = result['new_offset']
        return result

    def post(self, content, qualifier=':', limited_to = None, no_comments = None, lang = 'tr_ch'):
        if len(content) > 140:
            result = self.plurkAdd(content[0:140], qualifier, limited_to, no_comments, lang)
            self.response(result['plurk_id'],content[140:],qualifier)
        else:
            result = self.plurkAdd(content, qualifier, limited_to, no_comments, lang)
        return result

    def response(self, plurk_id, content, qualifier):
        while len(content) > 140:
            self.responseAdd(plurk_id,content[0:140], qualifier)
            content = content[140:]
        self.responseAdd(plurk_id, content, qualifier)

    def __make_new_listen_url(self):
        if(self.__user_channel == None):
            response = self.getUserChannel()
            self.__user_channel = response['comet_server']
        return '{}{}'.format(self.__user_channel.rstrip('0'),self.__offset)